﻿using SarjetLib;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Timer = System.Windows.Forms.Timer;

namespace WelineDynamicIP_LinkSmb
{
  public partial class main : Form
  {
    public main()
    {
      this.FormBorderStyle = FormBorderStyle.Fixed3D;
      this.MaximizeBox = false;
      this.WindowState = FormWindowState.Minimized;
      this.StartPosition = FormStartPosition.CenterScreen;
      this.Width = 120;

      InitializeComponent();
    }

    private void main_Load(object sender, EventArgs e)
    {
      WelineHandle wl = new WelineHandle();
      if (wl.OpenWelined())
      {
        AutoClick(cmState.OpenWeline);
      }
      //var addr = $@"\\198.18.1.47\sarjet89\mnt";
      //wl.OpenMnt(addr);
      this.Activated += new EventHandler((obj1, e1) =>
      {
        Timer tevt = new Timer();
        tevt.Interval = 500;
        tevt.Enabled = true;
        tevt.Tick += new EventHandler((obj2, e2) =>
        {
          tevt.Enabled = false;
          this.WindowState = FormWindowState.Minimized;
          btnIP_Click(this, e1);
        });
      });
      this.FormClosing += new FormClosingEventHandler((obj, e1) => { g_threadClose = true; });
      Thread t = new Thread(() =>
      {
        while (!g_threadClose)
        {
          var addrcomb = Path.Combine(g_addDir1, g_addDir2);
          var addr = Path.Combine($@"\\{g_ip}", addrcomb);
          var addrz = Path.Combine(g_mapDriver, g_addDir2);
          bool d1 = Directory.Exists(addr);
          bool d2 = Directory.Exists(addrz);
          if (!d1)
          {
            Action<string> progress = new Action<string>((string s) =>
            {
              this.Invoke((MethodInvoker)(() => { this.Text = $"{s}"; }));
            });
            SambaMapDriverInfo_t samba = new SambaMapDriverInfo_t(g_user, g_password, g_addDir1, g_mapDriver[0]);
            bool r = wl.WelineIpGet(samba, addrcomb, ref g_ip, progress);
            this.Invoke((MethodInvoker)(() =>
            {
              if (r)
              {
                g_state = cmState.IP;
                btnIP.Text = g_ip;
                this.Text = g_ip;
              }
              else
              {
                g_state = cmState.OpenWeline;
                btnIP.Text = this.Text; // = "open weline";
              }
            }));
          }
          if (false)
          {
            g_threadClose = true;
            Application.Exit();
            continue;
          }
          Thread.Sleep(10000);
        }
      });
      t.IsBackground = true;
      t.Start();
    }

    private void btnIP_Click(object sender, EventArgs e)
    {
      AutoClick(g_state);
    }

    private void AutoClick(cmState state)
    {
      WelineHandle wl = new WelineHandle();
      switch (state)
      {
        case cmState.OpenWeline:
          string weline = @"C:\Program Files\Weline\WelineUI.exe";
          if (File.Exists(weline))
          {
            WelineHandle.StartExe(weline, "", out var err, 0);
            Thread.Sleep(3000);
            IntPtr MyHwnd = WelineHandle.FindWindow(null, "WelineUI");
            if (MyHwnd != IntPtr.Zero)
            {
              //WelineHandle.SendMessage(MyHwnd, WelineHandle.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
          }
          this.WindowState = FormWindowState.Minimized;
          break;
        case cmState.IP:
          var addrcomb = Path.Combine(g_addDir1, g_addDir2);
          var addr = Path.Combine($@"\\{btnIP.Text}", addrcomb);
          if (Directory.Exists(g_mapDriver))
          {
            wl.OpenMnt(g_mapDriver);
          }
          else if (Directory.Exists(addr))
          {
            wl.OpenMnt(addr);
          }
          this.WindowState = FormWindowState.Minimized;
          break;
      }
    }

    public string g_ip;
    public string g_user = @"sarjet89";//samba账号
    public string g_password = @"123456";//samba密码
    public string g_mapDriver = @"z:\";//映射到盘符
    public string g_addDir1 = @"home";//这里是固件1.2.5-1版本默认的私有文件夹
    public string g_addDir2 = @"mnt"; //这里是你的目录下映射的一个指定文件夹(首次使用需要创建)
    public bool g_threadClose = false;

    public enum cmState
    {
      None,
      IP,
      OpenWeline,
    }
    public cmState g_state = cmState.None;
  }
}
